<?php
namespace app\client\controller;

class Login {
    public function login(){

        $code = request()->post('code', '', 'trim');
        if($code === ''){
            return errorResult();
        }
        
        $wxConfig = config('config.wx');
        
        $ch = curl_init("https://api.weixin.qq.com/sns/jscode2session?appid={$wxConfig['appid']}&secret={$wxConfig['secret']}&js_code={$code}&grant_type=authorization_code");
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        $result = curl_exec($ch);
        curl_close($ch);

        unset($ch);
        unset($wxConfig);

       if(!$result){ //获取微信信息失败
            return errorResult('登录失败1');
        }
        
        $result = json_decode($result, true);
        
        if(!$result || isset($result['errcode'])){
            return errorResult('登录失败2');
        }
        
        $unionid = isset($result['unionid']) ? trim($result['unionid']) : '';
        $openid = $result['openid'];
        $session_key = $result['session_key'];
        
        $userModel = model('User');
        $time = time();
        
        //用户
        $user = $userModel->findOne(['openid' => $openid], ['user_id', 'unionid']);

        if(empty($user)){ //没有的
            
            $userModel->startTrans();
            
            $data = ['register_time' => $time, 'session_key' => $session_key, 'last_login_time' => $time, 'openid' => $openid, 'unionid' => $unionid];
            if(!empty($unionid)) {
                $data['unionid'] = $unionid;
            }
            
            $userId = $userModel->add($data);
            
            if(!$userId){
                $userModel->rollback();
                return errorResult('登录失败3');
            }
            
            $walletId = model('UserWallet')->add(['user_id' => $userId]);
            
            if(!$walletId){
                $userModel->rollback();
                return errorResult('登录失败4');
            }
            
            $userModel->commit();
            
        }else{ //已经有了
            $userId = $user['user_id'];
            $data = ['last_login_time' => $time, 'session_key' => $session_key];
            if(empty($user['unionid']) && !empty($unionid)){
                $data['unionid'] = $unionid;
            }
            $userModel->modify(['user_id' => $userId], $data);
        }
        
        unset($userModel);
        
        $signer = new \Lcobucci\JWT\Signer\Hmac\Sha256();
        $builder = new \Lcobucci\JWT\Builder();
        $builder->setIssuer('易伙');
        $builder->setAudience('易伙');
        $builder->setId($userId * 520, true); //自定义标识
        $builder->setIssuedAt($time);
        $builder->set('key',base64_encode($userId * 1030));
        $builder->sign($signer,config("config.jwtKey"));
        $token = $builder->getToken()->__toString();
        
        
        return successResult(['token' => $token]);
    }
}












